/**
 * 
 */
package com.duowan.cms.service.ip;

import org.springframework.stereotype.Service;

import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.webapp.property.ExtendedPropertyPlaceholderConfigurer.PropertiesHolder;

/**
 * @author yzq
 *
 */
@Service("ipService")
public class IpServiceImpl implements IpService {

    @Override
    public boolean isInnerIP(String givenIp) {
        
        if(StringUtil.isEmpty(givenIp)){
            return false;
        }
        
        String[] ips = PropertiesHolder.get("innerIp", "183.60.177.225-183.60.177.254;210.21.125.41-210.21.125.46;127.0.0.1").split(";|,");
        
        for(String ip : ips){
            if(ip.indexOf("-") > 0){//ip段
                String[] ip_part = ip.split("-");
                if(isInIpPart(ip_part[0], ip_part[1], givenIp)){
                    return true;
                }
            }else{//ip值
                if(givenIp.equals(ip.trim())){
                    return true;
                }
            }
        }
        
        return false;
    }
    
    private boolean isInIpPart(String startIp, String endIp, String givenIp){
        
        String[] min = startIp.trim().split("\\.");
        String[] max = endIp.trim().split("\\.");
        String[] given = givenIp.trim().split("\\.");
        
        for(int i = 0; i < 4; i++){
            if(Integer.parseInt(min[i]) > Integer.parseInt(given[i]) || Integer.parseInt(given[i]) > Integer.parseInt(max[i])){
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        System.out.println(new IpServiceImpl().isInnerIP("183.60.177.227"));
    }
    
    
}
